import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient, HttpHandler, HttpErrorResponse, HttpRequest, HttpResponse } from '@angular/common/http';
// import { NzNotificationService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { filter } from 'rxjs/operators';
import { Demand } from '../../classes/demand';
import { Page } from '../../classes/page';
import { HubService } from '../../services/hub.service';
import { DemandService } from '../../services/demand.service';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { ROOT_URL } from '../../app.config';

@Component({
  selector: 'app-order-details',
  templateUrl: './order.details.component.html',
  styleUrls: ['./order.details.component.css']
})

export class OrderDetailsComponent implements OnInit, OnDestroy {
  demand: Demand;
  validateForm: FormGroup;
  isVisible = false;
  isConfirmLoading = false;
  isDisabled = false;

  uploading = false;
  fileList: UploadFile[] = [];

  observerHandle: Subscription;
  message: string;
  constructor(
    private http: HttpClient,
    private fb: FormBuilder,
    private demandService: DemandService,
    private hubService: HubService,
    private msg: NzMessageService
  ) { }

  ngOnInit() {
    this.validateForm = this.fb.group({
      result: [null, [Validators.required]],
      description: [null],
    });
  }

  onShow(demand: Demand): void {
    this.demand = demand;
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  ngOnDestroy() {
    if (this.observerHandle) {
      this.observerHandle.unsubscribe();
    }
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList.push(file);
    return false;
  }

  handleOk(): void {
    const formData = new FormData();
    formData.append('id', this.demand.id);
    formData.append('result', this.validateForm.value.result);
    formData.append('description', this.validateForm.value.description);
    // tslint:disable-next-line:no-any
    this.fileList.forEach((file: any) => {
      formData.append('files', file);
    });
    this.uploading = true;
    // You can use any AJAX library you like
    const request = new HttpRequest('POST', ROOT_URL + '/demand/server/handle', formData, {
      // reportProgress: true
    });
    this.http
      .request(request)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        (event: {}) => {
          this.uploading = false;
          this.msg.success('upload successfully.');
        },
        err => {
          this.uploading = false;
          this.msg.error('upload failed.');
        }
      );
  }

}
